import { Service } from 'egg';
// import * as bcrypt from 'bcryptjs';
import { RESULT_CODE } from '../utils/constants/code';

export default class AuthService extends Service {
  /**
   * 用户注册
   */
  async register(mobile: string, userName: string, password: string) {
    const { ctx } = this;

    // 检查手机号是否已存在
    const existUser = await ctx.model.User.findOne({
      where: { mobile },
    });

    if (existUser) {
      ctx.throw(RESULT_CODE.FAIL, '手机号已被注册');
    }

    // 加密密码
    // const hashedPassword = await bcrypt.hash(password, 10);

    // 创建用户
    const user = await ctx.model.User.create({
      mobile,
      user_name: userName,
      password: password,
      is_admin: 0,
    });

    return {
      user_id: user.user_id || user.id,
      user_name: user.user_name,
      mobile: user.mobile,
    };
  }

  /**
   * 用户登录
   */
  async login(mobile: string, password: string) {
    const { ctx, app } = this;

    // 查找用户
    const user = await ctx.model.User.findOne({
      where: { mobile, status: 1 },
    });
    

    if (!user || null == user) {
      ctx.throw(RESULT_CODE.FAIL, '用户不存在或已被禁用');
    }

    // 验证密码
    const isPasswordValid = password === user!.password // await bcrypt.compare(password, user!.password);
    if (!isPasswordValid) {
      ctx.throw(RESULT_CODE.FAIL, '密码错误');
    }

    // 生成JWT token
    const token = app.jwt.sign(
      {
        user_id: user!.user_id || user!.id,
        user_name: user!.user_name,
        mobile: user!.mobile,
        is_admin: user!.is_admin,
      },
      app.config.jwt.secret,
      { expiresIn: app.config.jwt.sign.expiresIn }
    );

    return {
      token,
      user: {
        user_id: user!.user_id || user!.id,
        user_name: user!.user_name,
        mobile: user!.mobile,
        is_admin: user!.is_admin,
      },
    };
  }

  /**
   * 获取用户信息
   */
  async getUserInfo(userId: number) {
    const { ctx } = this;

    const user = await ctx.model.User.findByPk(userId, {
      attributes: ['user_id', 'mobile', 'user_name', 'is_admin', 'status', 'created_at', 'avatar'],
    });

    if (!user) {
      ctx.throw(404, '用户不存在');
    }

    return {
      user_id: user!.user_id || user!.id,
      user_name: user!.user_name,
      mobile: user!.mobile,
      is_admin: user!.is_admin,
      status: user!.status,
      avatar: user?.avatar ? this.config.host + user?.avatar : '',
      created_at: user!.created_at,
    };
  }
}